package com.xxxy.jsq.action.term;

import com.xxxy.jsq.dao.TermDao;
import com.xxxy.jsq.model.Term;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Date;

@WebServlet("/addTermServlet")
public class addTermServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public addTermServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码，避免中文乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 创建学期DAO对象
        TermDao dao = new TermDao();
        // 创建学期模型对象
        Term model = new Term();

        // 获取页面传递的参数（与前端表单字段名保持一致）
        String termName = request.getParameter("tname");   // 学期名称
        String termFlag = request.getParameter("tflag");   // 状态
        String termOrderStr = request.getParameter("torder"); // 排序

        // 设置模型对象属性
        if (termName != null && !termName.equals("")) {
            model.setTermName(termName);
        }
        if (termFlag != null && !termFlag.equals("")) {
            model.setTermFlag(termFlag);
        }
       if (termOrderStr != null && !termOrderStr.equals("")) {
            model.setTermOrder(Integer.parseInt(termOrderStr));
        }
        // 设置时间戳为当前时间
        model.setTermStmp(new Timestamp(new Date().getTime()));

        // 调用DAO层的添加方法
        String result = dao.add(model);

        // 返回处理结果给前端
        PrintWriter out = response.getWriter();
        out.print(result);  // 返回"Ok"表示成功，"Same"表示名称重复，"Err"表示失败
        out.flush();
        out.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // POST请求也交给doGet处理
        doGet(request, response);
    }
}